<template>
    <div class="mbDemo">
        <div class="wrap">
            <div class="actionsWrap">
                <div class="actions">
                    <button @click="handleBack">返回</button>
                    <button class="danger" @click="handleClear">清空</button>
                    <button class="primary" @click="handlePreview">确定</button>
                </div>
            </div>
            <canvas class="canvas" id="canvas2" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, defineEmits } from 'vue';
import SmoothSignature from 'smooth-signature';

let signature: any;

const emit = defineEmits(['getPngUrl', "back"]);


const initSignature = () => {
    const canvas = document.getElementById('canvas2') as HTMLCanvasElement;
    const options = {
        width: window.innerWidth - 100,
        height: window.innerHeight - 50,
        minWidth: 3,
        maxWidth: 10,
        bgColor: '#fff',
    };
    signature = new SmoothSignature(canvas, options);
};


const handleClear = () => {
    signature.clear();
};


const handleBack = () => {
    emit('back')
}

const handlePreview = () => {
    const isEmpty = signature.isEmpty();
    if (isEmpty) {
        alert('isEmpty');
        return;
    }
    const canvas = signature.getRotateCanvas(-90);
    const pngUrl = canvas.toDataURL();
    emit('getPngUrl', pngUrl); // 触发事件，将 pngUrl 传递给父组件
    // window.previewImage(pngUrl, 90);
};

onMounted(() => {
    initSignature();
});
</script>

<style lang="less">
.mbDemo {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;

    button {
        font-size: 18px;
    }

    canvas {
        border-radius: 10px;
        border: 2px dashed #ccc;
    }

    .wrap {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        padding: 15px;
        display: flex;
        justify-content: center;

        .actionsWrap {
            width: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .canvas {
            flex: 1;
        }

        .actions {
            margin-right: 10px;
            white-space: nowrap;
            transform: rotate(90deg);

            .danger {
                background: red;
                color: #fff
            }

            .primary {
                background: #1875FE;
                color: #fff
            }

            button {
                margin-left: 10px;
                border: none;
                font-size: 12px;
                padding: 2px 10px;
                border-radius: 4px;
            }
        }
    }
}
</style>